package com.mg.game;

import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.World;

import com.mg.framework.kernel.Screen;
import com.mg.framework.kernel.WorldConstant;

public class GameWorld {

	private PolygonShape box = null;
	private World world = null;
	private BodyDef bodyDef = null;
	private Screen screen = null;

	public GameWorld(Screen screen) {
		this.box = new PolygonShape();
		this.bodyDef = new BodyDef();
		this.world = new World(WorldConstant.gravity, true);
		this.screen = screen;
	}

	public Body createBoxBody(float x, float y, int w, int h,
			boolean isDynamic, float density) {
		this.box.setAsBox(w / 2 / WorldConstant.ratio, h / 2
				/ WorldConstant.ratio);
		if (isDynamic) {
			this.bodyDef.type = BodyType.DYNAMIC;
		} else {
			this.bodyDef.type = BodyType.STATIC;
		}
		this.bodyDef.position.set((x + w / 2) / WorldConstant.ratio,
				(y + h / 2) / WorldConstant.ratio);
		Body body = world.createBody(bodyDef);
		body.createFixture(this.box, density);
		return body;
	}

	public void step() {
		this.world.step(WorldConstant.timeStep,
				WorldConstant.velocityIterations,
				WorldConstant.positionIterations);
	}

	public Box[][] createBoxs() {
		int i = 0, j = 0;
		float x = 100, y = 0;
		int w = 20, h = 20;
		boolean isDynamic = true;
		float density = 10;

		Box[][] boxs = new Box[1][2];

		while (i < 1) {
			j = 0;
			while (j < 2) {
				boxs[i][j] = new Box(this.createBoxBody(x + j * w, y + i * h, w, h,
						isDynamic, density), this.screen, w, h);
				j++;
			}
			i++;
		}
		return boxs;
	}
	
	public Box createBox(float x, float y,int w, int h, boolean isDynamic,float density) {
		return new Box(this.createBoxBody(x, y, w, h,
						isDynamic, density), this.screen, w, h);
	}
}